//package com.jn.rxjava.views;
//
//import android.content.Intent;
//import android.os.Bundle;
//import android.text.Editable;
//import android.text.TextWatcher;
//import android.util.Log;
//import android.view.View;
//import android.widget.AdapterView;
//import android.widget.ArrayAdapter;
//import android.widget.Button;
//import android.widget.EditText;
//import android.widget.ListView;
//
//import androidx.appcompat.app.AppCompatActivity;
//
//
//import com.jn.rxjava.R;
//import com.qweather.sdk.bean.base.Lang;
//import com.qweather.sdk.bean.base.Range;
//import com.qweather.sdk.bean.geo.GeoBean;
//import com.qweather.sdk.view.QWeather;
//
//import java.util.ArrayList;
//import java.util.List;
//
//public class SearchCityActivity extends AppCompatActivity {
//
//    private EditText etSearchCity;
//    private ListView lvCities;
//    private Button back_button;
//    private ArrayAdapter<GeoBean.LocationBean> adapter;
//    private List<GeoBean.LocationBean> cityList = new ArrayList<>();
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_searchcity);
//        back_button = findViewById(R.id.back_weather);
//        etSearchCity = findViewById(R.id.et_search_city);
//        lvCities = findViewById(R.id.lv_cities);
//
//        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, cityList);
//        lvCities.setAdapter(adapter);
//
//        etSearchCity.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                searchCity(s.toString());
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//            }
//        });
//
//        lvCities.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                GeoBean.LocationBean city = cityList.get(position);
//                String cityId = city.getId();
//                String cityName = city.getName();
//
//                Intent intent = new Intent();
//                intent.putExtra("cityId", cityId);
//                intent.putExtra("cityName", cityName);
//                setResult(RESULT_OK, intent);
//                finish();
//            }
//        });
//        back_button.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                onBackPressed();
//            }
//        });
//    }
//
//    private void searchCity(String keyword) {
//        QWeather.getGeoCityLookup(this, keyword, null, Range.CN, 10, Lang.ZH_HANS, new QWeather.OnResultGeoListener() {
//            @Override
//            public void onError(Throwable e) {
//                Log.e("SearchCity", "Error: " + e.getMessage());
//            }
//
//            @Override
//            public void onSuccess(GeoBean geoBean) {
//                if ("200".equals(geoBean.getCode())) {
//                    cityList.clear();
//                    cityList.addAll(geoBean.getLocationBean());
//                    adapter.notifyDataSetChanged();
//                } else {
//                    Log.e("SearchCity", "Failed to fetch cities: " + geoBean.getCode());
//                }
//            }
//        });
//    }
//}
package com.jn.rxjava.views;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.jn.rxjava.R;
import com.jn.rxjava.adapter.CityAdapter;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.base.Range;
import com.qweather.sdk.bean.geo.GeoBean;
import com.qweather.sdk.view.QWeather;

import java.util.ArrayList;
import java.util.List;

public class SearchCityActivity extends AppCompatActivity {

    private EditText etSearchCity;
    private ListView lvCities;
    private Button back_button;
    private CityAdapter adapter;
    private List<GeoBean.LocationBean> cityList = new ArrayList<>();
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable searchRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchcity);
        back_button = findViewById(R.id.back_weather);
        etSearchCity = findViewById(R.id.et_search_city);
        lvCities = findViewById(R.id.lv_cities);

        if (!isNetworkAvailable()) {
            Toast.makeText(this, "请检查网络连接", Toast.LENGTH_SHORT).show();
            return;
        }

        adapter = new CityAdapter(this, cityList);
        lvCities.setAdapter(adapter);

        etSearchCity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (searchRunnable != null) {
                    handler.removeCallbacks(searchRunnable);
                }
                searchRunnable = () -> searchCity(s.toString());
                handler.postDelayed(searchRunnable, 500); // 延迟500毫秒后执行搜索
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        etSearchCity.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                String keyword = etSearchCity.getText().toString().trim();
                if (!keyword.isEmpty()) {
                    searchCity(keyword);
                }
                return true;
            }
            return false;
        });

        lvCities.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GeoBean.LocationBean city = cityList.get(position);
                String cityId = city.getId();
                String cityName = city.getName();

                Intent intent = new Intent();
                intent.putExtra("cityId", cityId);
                intent.putExtra("cityName", cityName);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        back_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    private void searchCity(String keyword) {
        Log.d("SearchCity", "Searching for: " + keyword);
        QWeather.getGeoCityLookup(this, keyword, null, Range.CN, 10, Lang.ZH_HANS, new QWeather.OnResultGeoListener() {
            @Override
            public void onError(Throwable e) {
                Log.e("SearchCity", "Error: " + e.getMessage(), e);
                runOnUiThread(() -> Toast.makeText(SearchCityActivity.this, "搜索出错: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onSuccess(GeoBean geoBean) {
                final String responseCode = geoBean.getCode().getCode();
                Log.d("SearchCity", "Response code: " + responseCode);
                if ("200".equals(responseCode)) {
                    final List<GeoBean.LocationBean> locations = geoBean.getLocationBean();
                    runOnUiThread(() -> {
                        cityList.clear();
                        cityList.addAll(locations);
                        adapter.notifyDataSetChanged();
                        Log.d("SearchCity", "Found " + cityList.size() + " cities");
                    });
                } else {
                    runOnUiThread(() -> {
                        Log.e("SearchCity", "Failed to fetch cities: " + responseCode);
                        Toast.makeText(SearchCityActivity.this, "搜索失败: " + responseCode, Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }
}